<template>
    <div style="width: 100%;height: 100%;">
      <div id="container">
        <div style="top: 20%;left:80%;border-radius: 5px;padding:30px 15px 15px 20px;box-sizing: border-box;border: 1px solid #3F96A5;box-shadow: inset 0px 0px 20px 0px rgba(63, 150, 165, 0.5);background: #021322;;height: 42vh;width: 10vw;position: relative;z-index:999">
          <div><h4>基本信息</h4></div>
          <div style="display:flex;margin-top: 20px">
            <img src="../../../public/images/wg.png" style="width: 20%">
            <div style="margin-left: 10%"><h4>网格数量</h4></div>
          </div>
          <div style="margin-left: 30%"><h3>{{sumFormLevel.gridCount}}</h3></div>
          <div style="display:flex;margin-top: 20px">
            <img src="../../../public/images/zyz.png" style="width: 20%">
            <div style="margin-left: 10%"><h4>志愿者数量</h4></div>
          </div>
          <div style="margin-left: 30%"><h3>{{sumFormLevel.volunteerCount}}</h3></div>
          <div style="display:flex;margin-top: 20px">
            <img src="../../../public/images/wg.png" style="width: 20%">
            <div style="margin-left: 10%"><h4>事件上报数量</h4></div>
          </div>
          <div style="margin-left: 30%"><h3>{{sumFormLevel.event}}</h3></div>
          <div style="display:flex;margin-top: 20px">
            <img src="../../../public/images/wg.png" style="width: 20%">
            <div style="margin-left: 10%"><h4>事件办结数量</h4></div>
          </div>
        <div style="margin-left: 30%"><h3>{{sumFormLevel.Completion}}</h3>
        </div>

      </div>
      </div>
      <div class="infoTop">
        <img src="../../../public/images/start.png" style="width: 1.4vw;margin-right: 0.4vw">
        <span style="cursor:pointer;" v-for="(item,index) in recordsLog" :key="item.name" >
                  <span @click="handleTap(item,index)">{{item.name}}</span>
                  {{recordsLog.length - 1 === index ? '' : '-'}}</span>
      </div>
      <div class="tips"><span style="color: orange;">橙色</span>为意向合作地区，<span style="color: red;">红色</span>为已经开通服务地区</div>
    </div>
  </template>
<script>
import { getGridLevelList, getLastGridLevelList } from '@/network/request'
const opts = {
  subdistrict: 1,
  showbiz: false,
  extensions: 'all'
}
const layerOpts = {
  // 开启标注避让，默认为开启，v1.4.15 新增属性
  collision: false,
  // 开启标注淡入动画，默认为开启，v1.4.15 新增属性
  animation: true
}
// 安源区 矩形范围
const anyuanBounds = new AMap.Bounds(
  // [113.769626, 27.541738],
  // [113.996287, 27.721883]
  [113.769626, 27.541738],
  [113.996287, 27.721883]
)

// 图层数据集合
const ImageLayerMap = {
  安源区: {
    name: '安源区',
    url: require('../../../public/images/anyuan6.png'),
    bounds: anyuanBounds
  },
  白源街道: {
    name: '白源街道',
    url: require('../../../public/images/baiyuanjiedao1.png'),
    bounds: anyuanBounds
  },
  横龙街道: {
    name: '横龙街道',
    url: require('../../../public/images/henglongjiedao1.png'),
    bounds: anyuanBounds
  },
  安源镇: {
    name: '安源镇',
    url: require('../../../public/images/anyuanzhen1.png'),
    bounds: anyuanBounds
  },
  青山镇: {
    name: '青山镇',
    url: require('../../../public/images/qinshanzhen1.png'),
    bounds: anyuanBounds
  },
  高坑镇: {
    name: '高坑镇',
    url: require('../../../public/images/gaokenzhen1.png'),
    bounds: anyuanBounds
  },
  丹江街道: {
    name: '丹江街道',
    url: require('../../../public/images/danjiangjiedao1.png'),
    bounds: anyuanBounds
  },
  八一街道: {
    name: '八一街道',
    url: require('../../../public/images/bayijiedao1.png'),
    bounds: anyuanBounds
  },
  光丰街道: {
    name: '光丰街道',
    url: null,
    bounds: anyuanBounds
  },
  五陂镇: {
    name: '五陂镇',
    url: require('../../../public/images/wupozhen1.png'),
    bounds: anyuanBounds
  },
  凤凰街道: {
    name: '凤凰街道',
    url: require('../../../public/images/fenghuangjiedao1.png'),
    bounds: anyuanBounds
  },
  东大街道: {
    name: '东大街道',
    url: require('../../../public/images/dongdajiedao1.png'),
    bounds: anyuanBounds
  },
  后埠街道: {
    name: '后埠街道',
    url: require('../../../public/images/houbujiedao1.png'),
    bounds: anyuanBounds
  }
}

// 意向合作区域 list
const netDataName = ['贵州省', '毕节市', '大方县', '赫章县', '金沙县', '纳雍县', '七星关区', '织金县', '铜仁市', '印江自治县',
  '湖北省', '恩施土家族苗族自治州', '鹤峰县', '咸丰县', '宣恩县', '宜昌市', '巴东县', '重庆市', '沿河土家族自治县',
  '十堰市', '竹溪县',
  // '四川省','凉山彝族自治州','马边县','巴中市','平昌县'
  '赣州市', '石城县', '遂川县', '兴国县',
  '湖南省', '株洲市', '炎陵县',
  '河南省', '许昌市', '建安区', '魏都区', '鄢陵县', '禹州市', '长葛市', '襄城县'
]
const netData = [
  // 貴州
  { regionName: '贵州省' },
  { regionName: '毕节市' },
  { regionName: '大方县' },
  { regionName: '赫章县' },
  { regionName: '金沙县' },
  { regionName: '纳雍县' },
  { regionName: '七星关区' },
  { regionName: '织金县' },
  { regionName: '铜仁市' },
  { regionName: '印江自治县' },
  // 湖北省
  { regionName: '湖北省' },
  { regionName: '恩施土家族苗族自治州' },
  { regionName: '鹤峰县' },
  { regionName: '咸丰县' },
  { regionName: '宣恩县' },
  { regionName: '宜昌市' },
  { regionName: '巴东县' },
  { regionName: '重庆市' },
  { regionName: '沿河土家族自治县' },

  { regionName: '十堰市' },
  { regionName: '竹溪县' },
  // 四川省
  // {regionName: '四川省'},
  // {regionName: '凉山彝族自治州'},
  // {regionName: '马边县'},
  // {regionName: '巴中市'},
  // {regionName: '平昌县'},
  // 江西省
  { regionName: '江西省' },
  { regionName: '赣州市' },
  { regionName: '石城县' },
  { regionName: '遂川县' },
  { regionName: '兴国县' },
  // 湖南省
  { regionName: '湖南省' },
  { regionName: '株洲市' },
  { regionName: '炎陵县' },

  // 河北省
  { regionName: '河南省' },
  { regionName: '许昌市' },
  { regionName: '建安区' },
  { regionName: '魏都区' },
  { regionName: '鄢陵县' },
  { regionName: '禹州市' },
  { regionName: '长葛市' },
  { regionName: '襄城县' }
]

export default {
  data () {
    return {
      form: {
        grid: 360,
        Completion: 165,
        event: 168,
        volunteer: 24645
      },
      amap: null,
      district: new AMap.DistrictSearch(opts),
      layer: new AMap.LabelsLayer(layerOpts),
      infoWindow: undefined,
      // 绑定事件集合
      polygonCache: {},
      polylineCache: {},
      imageLayerCache: {},
      districtLayerCache: {},
      markerCache: {},
      markerGridCache: [],
      recordsLog: [],
      districtSearchCache: {

      },
      labelsMarkerCache: {},
      // 记录地图初始化的时候的时候的层级，该层级不可修改 可选值 province,city,district,country,street
      initLevel: undefined,
      // 国，省，市，区，街道/镇 节点记录
      gridData: {},
      // 网格节点记录
      baseGridData: {},
      search: this.$route.query.search || '中华人民共和国',
      initRegionId: this.$route.query.id || 0
    }
  },
  mounted () {
    this.init(this.search)
  },
  computed: {
    getRecordsLevelFn () {
      return this[`recordLevel${this.initLevel}`]
    },
    // 根据当前level返回相应的统计数据
    sumFormLevel () {
      if (this.recordsLog.length === 0) return { gridCount: 0, Completion: 0, event: 0, volunteerCount: 0 }
      const { level, name } = this.recordsLog[this.recordsLog.length - 1]
      if (netDataName.includes(name)) {
        return { gridCount: 0, Completion: 0, event: 0, volunteerCount: 0 }
      }
      const resultFilter = Object.values(this.gridData).filter(n => {
        return n.level === level && (n.parName === name || !n.parName)
      })
      let resultObj = resultFilter.reduce((pre, cur) => {
        pre.gridCount += Number(cur.gridCount)
        pre.Completion += cur.Completion || 0
        pre.event += cur.event || 0
        pre.volunteerCount += Number(cur.volunteerCount || 0)
        return pre
      }, { gridCount: 0, Completion: 0, event: 0, volunteerCount: 0 })
      if (level === 'street') {
        const { gridCount, volunteerCount, Completion, event } = this.gridData[name]
        resultObj = { gridCount, Completion: Completion || 0, event: event || 0, volunteerCount }
      }
      return resultObj
    }
  },

  methods: {
    getGridLevelListFn ({ regionId, level, name }, cb) {
      getGridLevelList({ reginId: regionId }).then(res => {
        console.log(res, '========222')
        if (res.code === '200') {
          res.data.forEach(item => {
            this.$set(this.gridData, [item.regionName], { ...item, level, parName: name })
          })
          cb(res.data)
        }
      }).catch(e => {
        console.log(e, '==========')
        window.alert(`网络错误1:${e.message}`)
      })
    },
    getLastGridLevelListFn ({ regionId, level, name }, cb) {
      getLastGridLevelList({ townRegionId: regionId }).then(res => {
        if (res.code === '200') {
          res.data.forEach(item => {
            this.baseGridData[item.regionId] = item
            // this.$set(this.gridData, [item.regionName], { ...item, level, parName: name })
          })
          cb(res.data)
        }
      }).catch(e => {
        console.log(e, '==========')
        window.alert(`网络错误2:${e.message}`)
      })
    },
    // 页面初始化
    init (name) {
      // this.initImageLayer()
      this.initMap({ name, zooms: [4, 8], zoom: 4 })
    },
    // 初始化地图
    initMap ({ name, zoom, zooms }) {
      const that = this
      this.districtSearch(name, function (status, result) {
        console.log(result, 'result=============')
        that.districtSearchCache[name] = result
        const { center, level } = result.districtList[0]
        that.initLevel = level
        that.amap = new AMap.Map('container', {
          defaultCursor: 'pointer',
          expandZoomRange: true,
          viewMode: '3D',
          center: [center.lng, center.lat], // 地图中心点
          zoom: zoom, // 地图显示的缩放级别
          zooms: zooms, // 缩放级别范围
          // resizeEnable: true, // 是否监控地图容器尺寸变化
          mapStyle: 'amap://styles/darkblue', // 地图样式
          features: ['road', 'building', 'bg'] // bg point
        })
        that.amap.add(that.layer)
        that.levelControl(result.districtList[0])
        that.toolMap()
      })
    },
    // 给地图添加工具
    toolMap () {
      // 画框工具
      // this.RectangleTool()
      // 点击获取经纬度
      this.getLngLat()
    },

    RectangleTool () {
      var rectangle = new AMap.Rectangle({
        bounds: anyuanBounds,
        strokeColor: 'red',
        strokeWeight: 1,
        strokeOpacity: 0.5,
        strokeDasharray: [30, 10],
        // strokeStyle还支持 solid
        strokeStyle: 'dashed',
        fillColor: 'blue',
        fillOpacity: 0.5,
        cursor: 'pointer',
        zIndex: 50
      })
      this.amap.add(rectangle)
      var rectangleEditor = new AMap.RectangleEditor(this.amap, rectangle)

      rectangleEditor.on('adjust', function (event) {
        console.log('触发事件：adjust')
      })

      rectangleEditor.on('end', function (event) {
        console.log.info('触发事件： end')
        // event.target 即为编辑后的矩形对象
      })
      rectangleEditor.open()
    },
    getLngLat () {
      // 为地图注册click事件获取鼠标点击出的经纬度坐标
      this.amap.on('click', function (e) {
        console.log(`你点击了${e.lnglat}`)
      })
    },

    // 使用缓存在本地的数据，没有再去查
    districtSearch (name, callback) {
      if (this.districtSearchCache[name]) {
        console.log(`搜索${name}走缓存了`)
        callback(null, this.districtSearchCache[name])
      } else {
        console.log(`搜索${name}`)
        this.district.search(name, callback)
      }
    },

    // 提前生成图层 (暂时全量加载，后续可以懒加载)
    initImageLayer () {
      // if (ImageLayerMap[name] && ImageLayerMap[name].url) {
      //   const { url, bounds } = ImageLayerMap[name]
      //   const imageLayer = new AMap.ImageLayer({
      //     url,
      //     bounds,
      //     visible: false
      //   })
      //   this.imageLayerCache[name] = { name, imageLayer }
      // }
      // 提前缓存图片
      // Object.values(ImageLayerMap).forEach(event => {
      //   new Image().src = event.url
      // })
    },
    // 操作地图
    handleMap ({ name }) {
      const that = this
      this.districtSearch(name, function (status, result) {
        console.log(result, '-------')
        that.districtSearchCache[name] = result
        const { boundaries, center, districtList, level, adcode } = result.districtList[0]
        that.hideAndRemoveCache()
        that.levelControl(result.districtList[0])
      })
    },

    hideAndRemoveCache ({ imageLayerCache, markerCache } = {}) {
      // 隐藏地图资源 polygon
      Object.values(this.polygonCache).forEach(event => {
        event.polygon.hide()
      })
      // 隐藏地图资源 polyline
      Object.values(this.polylineCache).forEach(event => {
        event.polyline.forEach(n => n.hide())
      })
      // 隐藏地图资源 imageLayer
      Object.values(this.imageLayerCache).forEach(event => {
        !(imageLayerCache || []).includes(event.name) && event.imageLayer.hide()
      })
      // 隐藏地图资源 districtLayer
      Object.values(this.districtLayerCache).forEach(event => {
        event.districtLayer.hide()
      })
      // 隐藏地图资源 marker
      Object.values(this.markerCache).forEach(event => {
        !(markerCache || []).includes(event.name) && event.marker.hide()
      })
      // 删除地图资源 markerGrid
      // Object.values(this.markerGridCache).forEach(event => {

      // })
      this.amap.remove(this.markerGridCache)
      this.markerGridCache = []

      // 隐藏地图标注
      Object.values(this.labelsMarkerCache).forEach(event => {
        event.labelsMarker.hide()
      })
    },

    levelControl ({ boundaries, center, districtList, level, adcode, name }) {
      // console.log(`进入层级${name},${level}`)
      this.getRecordsLevelFn({ name, level, center })
      const parentArguments = arguments
      // province,city,district,country,street
      const regionId = this.gridData[name]?.regionId || this.initRegionId

      switch (level) {
        case 'province':
          this.getGridLevelListFn({ regionId, level, name }, (list) => {
            const _list = list.concat(netData)
            province.call(this, _list, ...parentArguments)
          })
          break
        case 'city':
          this.getGridLevelListFn({ regionId, level }, (list) => {
            const _list = list.concat(netData)
            city.call(this, _list, ...parentArguments)
          })
          break
        case 'district':
          this.getGridLevelListFn({ regionId, level }, (list) => {
            district.call(this, list, ...parentArguments)
          })
          break
        case 'country':
          console.log(24555555555)
          // 国家默认是 0
          this.getGridLevelListFn({ regionId: this.initRegionId, level }, (list) => {
            const _list = list.concat(netData)
            country.call(this, _list, ...parentArguments)
          })
          break
        case 'street':
          this.getLastGridLevelListFn({ regionId, level, name }, (list) => {
            street.call(this, list, ...parentArguments)
          })
          break
        default:
          break
      }

      function province (list, district) {
        const { center, districtList } = district
        const zoom = [6, 10]
        const showList = list.map(item => item.regionName)
        // 只展示有数据的区域
        const districtFilter = districtList.filter(item => showList.includes(item.name))
        this.mapLabelMarker(districtFilter, zoom)
        this.createDistrictProvinceLayer(district)
        this.mapPolygon(districtFilter)
        this.amap.setZooms(zoom)
        this.amap.panTo([center.lng, center.lat])
        this.amap.setZoom(7)
        // this.amap.setZoomAndCenter(7, [center.lng, center.lat])
      }
      function city (list, { boundaries, center, districtList, level, adcode, name }) {
        const zoom = [8, 12]
        const showList = list.map(item => item.regionName)
        // 只展示有数据的区域
        const districtFilter = districtList.filter(item => showList.includes(item.name))
        this.mapPolylineOrImageLayer(boundaries, name)
        this.mapLabelMarker(districtFilter, zoom)
        this.mapPolygon(districtFilter)
        this.amap.setZooms(zoom)
        this.amap.panTo([center.lng, center.lat])
        this.amap.setZoom(9)
        // this.amap.setZoomAndCenter(9, [center.lng, center.lat])
      }
      function district (list, { boundaries, center, districtList, level, adcode, name }) {
        const showList = list.map(item => item.regionName)
        // 筛选后台有数据的区域
        const districtFilter = districtList.filter(item => showList.includes(item.name))
        const districtFilterObj = {}
        districtFilter.forEach(item => {
          districtFilterObj[item.name] = item
        })
        // 使用后台返回的中心节点
        const markerList = list.map(n => {
          const center = n.longitude && n.latitude ? new AMap.LngLat(n.longitude, n.latitude) : districtFilterObj[name].center
          return {
            name: n.regionName,
            center,
            level: 'street'
          }
        })
        this.mapPolylineOrImageLayer(boundaries, name)
        this.amap.setZooms([12, 16])
        this.amap.panTo([center.lng, center.lat])
        this.amap.setZoom(13)
        // 创建街道中心点

        for (let i = 0; i < markerList.length; i++) {
          this.mapDistrictMarker(markerList[i])
          // this.mapDistrictMarker(districtFilter[i])
        }
      }
      function country (list, { boundaries, center, districtList, level, adcode, name }) {
        const zoom = [4, 8]
        const showList = list.map(item => item.regionName)
        // 只展示有数据的区域
        const districtFilter = districtList.filter(item => showList.includes(item.name))
        this.mapLabelMarker(districtFilter, zoom)
        this.createDistrictCountryLayer(name)
        this.mapPolygon(districtFilter)
        this.amap.setZooms(zoom)
        this.amap.panTo([center.lng, center.lat])
        this.amap.setZoom(4)
        // this.amap.setZoomAndCenter(4, [center.lng, center.lat])
      }
      function street (list, district) {
        const { center, level, name } = district
        // 创建 镇/街道 中心点
        this.mapDistrictMarker(district)
        this.mapPolylineOrImageLayer(null, name)

        this.amap.setZooms([12, 16])
        this.amap.panTo([center.lng, center.lat])
        this.amap.setZoom(14)

        list.forEach(item => {
          if (item.longitude && item.latitude) {
            this.mapGird(item)
          }
        })
      }
    },

    // province,city,district,country,street
    // 记录层级
    recordLevelcountry ({ name, level, center }) {
      const length = this.recordsLog.length
      switch (length) {
        case 0:
          // 没有记录的话，直接存入
          this.recordsLog.push({ name, level, center })
          break
        case 1:
          this.countryLevel({ name, level, center }, length)
          break
        case 2:
          this.provinceLevel({ name, level, center }, length)
          break
        case 3:
          this.cityLevel({ name, level, center }, length)
          break
        case 4:
          this.districtLevel({ name, level, center }, length)
          break
        case 5:
          this.streetLevel({ name, level, center }, length)
          break
        default:
          break
      }
    },
    recordLevelprovince ({ name, level, center }) {
      const length = this.recordsLog.length
      switch (length) {
        case 0:
          // 没有记录的话，直接存入
          this.recordsLog.push({ name, level, center })
          break
        case 1:
          this.provinceLevel({ name, level, center }, length)
          break
        case 2:
          this.cityLevel({ name, level, center }, length)
          break
        case 3:
          this.districtLevel({ name, level, center }, length)
          break
        case 4:
          this.streetLevel({ name, level, center }, length)
          break
        default:
          break
      }
    },
    recordLevelcity ({ name, level, center }) {
      const length = this.recordsLog.length
      switch (length) {
        case 0:
          // 没有记录的话，直接存入
          this.recordsLog.push({ name, level, center })
          break
        case 1:
          this.cityLevel({ name, level, center }, length)
          break
        case 2:
          this.districtLevel({ name, level, center }, length)
          break
        case 3:
          this.streetLevel({ name, level, center }, length)
          break
        default:
          break
      }
    },
    recordLeveldistrict ({ name, level, center }) {
      const length = this.recordsLog.length
      switch (length) {
        case 0:
          // 没有记录的话，直接存入
          this.recordsLog.push({ name, level, center })
          break
        case 1:
          this.districtLevel({ name, level, center }, length)
          break
        case 2:
          this.streetLevel({ name, level, center }, length)
          break
        default:
          break
      }
    },
    recordLevelstreet ({ name, level, center }) {
      const length = this.recordsLog.length
      switch (length) {
        case 0:
          // 没有记录的话，直接存入
          this.recordsLog.push({ name, level, center })
          break
        case 1:
          this.streetLevel({ name, level, center }, length)
          break
        default:
          break
      }
    },
    // 级别为country处理方式
    countryLevel ({ name, level, center }, length) {
      if (level === 'country') {
        // 已经存在记录并且是当前层级的话，替换
        const arr = this.recordsLog.slice(0, length - 1)
        this.recordsLog = arr.concat({ name, level, center })
        this.recordsLog = [{ name, level, center }]
      } else if (level === 'province') {
        // 后续是省级的话则直接push
        this.recordsLog.push({ name, level, center })
      }
    },

    provinceLevel ({ name, level, center }, length) {
      if (level === 'province') {
        // 已经存在记录并且是当前层级的话，替换
        const arr = this.recordsLog.slice(0, length - 1)
        this.recordsLog = arr.concat({ name, level, center })
      } else if (level === 'city') {
        // 后续是市级的话则直接push
        this.recordsLog.push({ name, level, center })
      }
    },

    cityLevel ({ name, level, center }, length) {
      if (level === 'city') {
        // 已经存在记录并且是当前层级的话，替换
        const arr = this.recordsLog.slice(0, length - 1)
        this.recordsLog = arr.concat({ name, level, center })
      } else if (level === 'district') {
        // 后续是市级的话则直接push
        this.recordsLog.push({ name, level, center })
      }
    },

    districtLevel ({ name, level, center }, length) {
      if (level === 'district') {
        // 已经存在记录并且是当前层级的话，替换
        const arr = this.recordsLog.slice(0, length - 1)
        this.recordsLog = arr.concat({ name, level, center })
      } else if (level === 'street') {
        // 后续是市级的话则直接push
        this.recordsLog.push({ name, level, center })
      }
    },

    streetLevel ({ name, level, center }, length) {
      if (level === 'street') {
        // 已经存在记录并且是当前层级的话，替换
        const arr = this.recordsLog.slice(0, length - 1)
        this.recordsLog = arr.concat({ name, level, center })
      }
    },

    // 创建简易行政区图层 国家级别
    createDistrictCountryLayer () {
      if (this.districtLayerCache[name]) {
        this.districtLayerCache[name].districtLayer.show()
      } else {
        const districtLayer = new AMap.DistrictLayer.Country({
          zIndex: 10,
          SOC: 'CHN',
          depth: 1,
          styles: {
            'nation-stroke': '#f09',
            'coastline-stroke': [0.85, 0.63, 0.94, 1],
            'province-stroke': 'white',
            'city-stroke': 'rgba(255,255,255,0.15)', // 中国特有字段
            fill: function (props) { // 中国特有字段
              return 'black'
            }
          }
        })
        this.amap.add(districtLayer)
        this.districtLayerCache[name] = { name, districtLayer }
      }
    },

    // 创建简易行政区图层 省份级别
    createDistrictProvinceLayer ({ adcode, name }) {
      if (this.districtLayerCache[name]) {
        this.districtLayerCache[name].districtLayer.show()
      } else {
        const districtLayer = new AMap.DistrictLayer.Province({
          zIndex: 10,
          adcode,
          depth: 1,
          styles: {
            'province-stroke': 'white',
            'city-stroke': 'white', // 中国地级市边界
            'county-stroke': 'black', // 中国区县边界
            fill: function (props) {
              return 'black'
            }
          }
        })
        this.amap.add(districtLayer)
        this.districtLayerCache[name] = { name, districtLayer }
      }
    },

    // 绘制边界 绘制边界的时候 如果有底图，则绘制底图
    mapPolylineOrImageLayer (bounds, name) {
      if (ImageLayerMap[name] && ImageLayerMap[name].url) {
        this.mapImageLayer(name)
      } else {
        bounds && this.mapPolyline(bounds, name)
      }
    },
    // 绘制底图
    mapImageLayer (name) {
      if (this.imageLayerCache[name]) {
        this.imageLayerCache[name].imageLayer.show()
      } else {
        if (ImageLayerMap[name] && ImageLayerMap[name].url) {
          const { url, bounds } = ImageLayerMap[name]
          const imageLayer = new AMap.ImageLayer({
            url,
            bounds
          })
          this.amap.add(imageLayer)
          this.imageLayerCache[name] = { name, imageLayer }
        }
      }
    },
    //  绘制边界
    mapPolyline (bounds, name) {
      if (this.polylineCache[name]) {
        this.polylineCache[name].polyline.forEach(n => n.show())
      } else {
        // 添加描边
        const polyLines = []
        for (let i = 0; i < bounds.length; i++) {
          const polyline = new AMap.Polyline({
            path: bounds[i], // polyline 路径，支持 lineString 和 MultiLineString
            strokeColor: '#fff',
            strokeWeight: 4
          })
          polyLines.push(polyline)
        }
        this.amap.add(polyLines)
        this.polylineCache[name] = { name, polyline: polyLines }
      }
    },
    // 绘制区域
    mapPolygon (districtList) {
      const that = this
      for (let i = 0; i < districtList.length; i++) {
        const { name } = districtList[i]
        if (that.polygonCache[name]) {
          that.polygonCache[name].polygon.show()
        } else {
          this.district.search(name, function (status, result) {
            const { boundaries, level, name } = result.districtList[0]
            let polygon
            if (boundaries) {
              for (var i = 0; i < boundaries.length; i += 1) { // 构造MultiPolygon的path
                boundaries[i] = [boundaries[i]]
              }
              const color = netDataName.includes(name) ? 'orange' : '#FF0000'
              polygon = new AMap.Polygon({
                path: boundaries,
                strokeColor: '#fff',
                strokeWeight: 1,
                strokeOpacity: 0.4,
                fillOpacity: 0.4,
                fillColor: color,
                zIndex: 50,
                bubble: true
              })
              that.amap.add(polygon)
              polygon.on('mouseover', (e) => {
                polygon.setOptions({
                  fillOpacity: 0.4,
                  fillColor: '#1791fc'
                })
                that.openInfo(name, e.lnglat, level)
              })
              polygon.on('mouseout', (e) => {
                polygon.setOptions({
                  fillOpacity: 0.4,
                  fillColor: color
                })
                that.infoWindow && that.infoWindow.close()
              })
              polygon.on('click', (e) => {
                that.handleMap({ name })
              })
              // 收集事件
              that.polygonCache[name] = { name, polygon }
            }
            // const polygon = new AMap.Polygon({
            //   path: boundaries.flat(1).map(n => [n.lng, n.lat]),
            //   strokeColor: '#fff',
            //   strokeWeight: 3,
            //   strokeOpacity: 0.4,
            //   fillOpacity: 0.4,
            //   fillColor: '#1791fc',
            //   zIndex: 50,
            //   bubble: true
            // })
            // that.amap.add(polygon)
          })
        }
      }
    },

    // 鼠标悬浮打开信息窗体
    openInfo (name, center, level, reginId) {
      let gridData
      if (level === 'grid') {
        gridData = this.baseGridData[reginId]
      } else {
        gridData = this.gridData[name]
      }

      if (!gridData) return
      const { gridCount, volunteerCount } = gridData
      // 构建信息窗体中显示的内容
      var info = []
      info.push(`<div style="border-radius: 5px;width: 345px;height: 163px;padding:30px 15px 15px 20px;box-sizing: border-box;border: 1px solid #3F96A5;box-shadow: inset 0px 0px 20px 0px rgba(63, 150, 165, 0.5);background: #021322;">
        <h4>${name}</h4>
        ${level === 'grid' ? '' : `<div style="color: #C0D2E2;margin-top: 30px"><h4>网格数：${gridCount || 0}个</h4></div>`}
        <div style="color: #C0D2E2;margin-top: 15px"><h4>志愿者人数：${volunteerCount || 0}人</h4></div>
      </div>`)
      this.infoWindow = new AMap.InfoWindow({
        isCustom: true,
        offset: new AMap.Pixel(10, -20),
        content: info.join('') // 使用默认信息窗体框样式，显示信息内容
      })
      this.infoWindow.open(this.amap, new AMap.LngLat(center.lng, center.lat))
    },

    // 创建 镇/街道 节点
    mapDistrictMarker ({ name, center, adcode, level }) {
      if (this.markerCache[name]) {
        this.markerCache[name].marker.show()
      } else {
        const that = this
        const marker = new AMap.Marker({ // 图标尺寸
          icon: '', // 点标记图片路径
          position: [center.lng, center.lat], // 位置
          topWhenClick: true,
          zIndex: 999
        })
        marker.setLabel({
          direction: 'bottom',
          offset: new AMap.Pixel(15, 20), // 设置文本标注偏移量
          content: `<div class="marker_label1" style="color:blue">${name}</div>` // 设置文本标注内容
        })
        this.amap.add(marker)
        marker.on('mouseover', (e) => {
        // 打开信息窗体
          that.openInfo(name, center, level)
        })
        marker.on('mouseout', (e) => {
        // 关闭信息窗体
          that.infoWindow && that.infoWindow.close()
        })
        marker.on('click', (e) => {
          that.hideAndRemoveCache({ imageLayerCache: [name], markerCache: [name] })
          that.levelControl({
            name,
            level,
            center
          })
        })
        this.markerCache[name] = { name, marker }
      }
    },

    // 创建网格 节点 不缓存节点，每次都重新创建
    mapGird ({ regionName, longitude, latitude, level, regionId }) {
      // baseGridData
      const icon = new AMap.Icon({
        size: new AMap.Size(54, 54), // 图标尺寸
        image: '/images/dw.png', // Icon的图像
        imageSize: new AMap.Size(62, 50) // 根据所设置的大小拉伸或压缩图片
        // imageOffset: new AMap.Pixel(0, 0) // 图像相对展示区域的偏移量，适于雪碧图等
      })
      const that = this
      const postion = new AMap.LngLat(longitude, latitude)
      const marker = new AMap.Marker({ // 图标尺寸
        icon: icon, // 点标记图片路径
        position: postion, // 位置
        topWhenClick: true,
        zIndex: 999
      })
      marker.setLabel({
        direction: 'bottom',
        offset: new AMap.Pixel(15, 20), // 设置文本标注偏移量
        content: `<div class="marker_label1" style="color:#fff">${regionName}</div>` // 设置文本标注内容
      })
      this.amap.add(marker)
      marker.on('mouseover', (e) => {
        // 打开信息窗体
        that.openInfo(regionName, postion, 'grid', regionId)
      })
      marker.on('mouseout', (e) => {
        // 关闭信息窗体
        that.infoWindow && that.infoWindow.close()
      })
      this.markerGridCache.push(marker)
    },
    mapLabelMarker (list, zoom) {
      list.forEach(item => {
        const { name, center, level } = item
        if (this.labelsMarkerCache[name]) {
          this.labelsMarkerCache[name].labelsMarker.show()
        } else {
          const config = {
            name: '',
            position: center,
            zooms: zoom,
            zIndex: 1,
            opacity: 1,
            text: {
              content: name,
              direction: 'center',
              offset: [0, 0],
              // zooms: [3, 20],
              style: {
                fontSize: 10,
                fontWeight: 'normal',
                fillColor: '#eee',
                strokeColor: '#88f',
                strokeWidth: 2
              }
            }
          }
          const color = netDataName.includes(name) ? 'orange' : '#FF0000'
          const labelsMarker = new AMap.LabelMarker(config)
          labelsMarker.on('click', (e) => {
            this.handleMap({ name })
          })

          labelsMarker.on('mouseover', (e) => {
            this.polygonCache[name].polygon.setOptions({
              fillOpacity: 0.4,
              fillColor: '#1791fc'
            })
            this.openInfo(name, e.lnglat, level)
          })
          labelsMarker.on('mouseout', (e) => {
            this.polygonCache[name].polygon.setOptions({
              fillOpacity: 0.4,
              fillColor: color
            })
            this.infoWindow && this.infoWindow.close()
          })

          this.layer.add(labelsMarker)
          this.labelsMarkerCache[name] = { name, labelsMarker }
        }
      })
    },

    handleTap ({ name, level, center }, index) {
      this.recordsLog = this.recordsLog.slice(0, index + 1)
      // street查询高德会出现重名 所以针对street额外处理
      if (level === 'street') {
        this.hideAndRemoveCache()
        this.levelControl({
          name,
          level,
          center
        })
      } else {
        this.handleMap({ name })
      }
    }
  }
}
</script>
<style lang="less">
.infoTop{
  background-color: #021322;
  color: #fff;
  height: 30px;
  line-height: 30px;
  font-size: 18px;
  margin-bottom: 1rem;
  border-radius: .25rem;
  position: fixed;
  top: 3rem;
  border-width: 0;
  //box-shadow: 0 2px 6px 0 rgba(114, 124, 245, .5);
}
.tips{
  height: 30px;
  line-height: 30px;
  font-size: 18px;
  margin-bottom: 1rem;
  border-radius: .25rem;
  position: fixed;
  bottom: 3rem;
  left: 50%;
  transform: translate(-50%);
}
.text{
  color: #1791fc;
  color: orange;
  color: rgb(255,165,0);
}
</style>
